<template>
  <div class="monitor">
    <!-- 系统负载部分 -->
    <div class="section system-load">
      <h2 class="section-title">系统负载</h2>
      <div class="system-overview">
        <!-- 左侧信息表格 -->
        <div class="info-table">
          <table>
            <tr>
              <td>CPU</td>
              <td>{{ systemInfo.cpuUsage }} {{ systemInfo.cpuFreq }}</td>
            </tr>
            <tr>
              <td>内存</td>
              <td>{{ systemInfo.usedMemory }}/{{ systemInfo.totalMemory }}</td>
            </tr>
            <tr>
              <td>硬盘</td>
              <td>{{ systemInfo.usedDiskspace }}/{{ systemInfo.totalDiskspace }}</td>
            </tr>
            <tr>
              <td>网络</td>
              <td>{{ systemInfo.networkSpeed }}</td>
            </tr>
          </table>
        </div>

        <!-- 右侧CPU使用率图表 -->
        <div class="chart-container">
          <h3>CPU利用率</h3>
          <v-chart class="cpu-chart" :option="cpuChartOption" autoresize />
        </div>
      </div>
    </div>

    <!-- 系统日志部分 -->
    <div class="section system-logs">
      <h2 class="section-title">系统日志</h2>
      <div class="log-container">
        <div v-if="Object.keys(logs).length > 0">
          <div v-for="(log, index) in logs" :key="index" class="log-entry" :class="getLogLevel(log)">
            {{ formatLogEntry(log) }}
          </div>
        </div>
        <div v-else class="no-logs">
          暂无日志信息
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { myAxios } from '../../axios/index'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import { GridComponent, TooltipComponent, TitleComponent } from 'echarts/components'
import VChart from 'vue-echarts'

use([
  CanvasRenderer,
  LineChart,
  GridComponent,
  TooltipComponent,
  TitleComponent
])

export default {
  name: 'SystemMonitor',
  components: {
    VChart
  },
  setup() {
    const systemInfo = ref({
      cpuUsage: '0%',
      cpuFreq: '0 GHz',
      totalMemory: '0 GB',
      usedMemory: '0 GB',
      totalDiskspace: '0 GB',
      usedDiskspace: '0 GB',
      networkSpeed: '0 M/s',
      temperature: '0°C'
    })

    const logs = ref([])
    let timer = null

    // CPU使用率历史数据
    const cpuHistory = ref([])
    const timeHistory = ref([])

    // CPU图表配置
    const cpuChartOption = reactive({
      grid: {
        top: 30,
        right: 20,
        bottom: 30,
        left: 50,
        containLabel: true
      },
      tooltip: {
        trigger: 'axis',
        formatter: '{b}: {c}%'
      },
      xAxis: {
        type: 'category',
        data: timeHistory,
        axisLine: {
          lineStyle: {
            color: '#475569'
          }
        },
        axisLabel: {
          color: '#94a3b8'
        }
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 100,
        splitLine: {
          lineStyle: {
            color: '#334155'
          }
        },
        axisLabel: {
          color: '#94a3b8',
          formatter: '{value}%'
        }
      },
      series: [{
        data: cpuHistory,
        type: 'line',
        smooth: true,
        symbol: 'none',
        lineStyle: {
          color: '#3b82f6'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(59,130,246,0.3)'
            }, {
              offset: 1,
              color: 'rgba(59,130,246,0.1)'
            }]
          }
        }
      }]
    })

    // 格式化日志条目
    const formatLogEntry = (log) => {
      return log.trim().replace(/\s+/g, ' ')
    }

    // 获取日志级别样式
    const getLogLevel = (log) => {
      if (log.includes('DEBUG')) return 'log-debug'
      if (log.includes('INFO')) return 'log-info'
      if (log.includes('WARNING')) return 'log-warning'
      if (log.includes('ERROR')) return 'log-error'
      return ''
    }

    // 获取系统资源信息
    const fetchSystemInfo = async () => {
      try {
        const response = await myAxios.get('/getSystemResources')
        if (response.data.code === 200) {
          const data = response.data.data
          console.log(data)
          // 更新系统信息
          systemInfo.value = {
            cpuUsage: data.cpuUsage,
            totalMemory: data.totalMemory,
            usedMemory: data.usedMemory,
            totalDiskspace: data.totalDiskSpace,
            usedDiskspace: data.usedDiskSpace,
            networkSpeed: '3.2M/s',
          }

          // 更新CPU历史数据
          const cpuValue = parseFloat(data.cpuUsage.replace('%', ''))
          cpuHistory.value.push(cpuValue)
          timeHistory.value.push(new Date().toLocaleTimeString('en-US', { 
            hour12: false,
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
          }))

          // 保持最近60个数据点
          if (cpuHistory.value.length > 60) {
            cpuHistory.value.shift()
            timeHistory.value.shift()
          }

          // 更新图表数据
          cpuChartOption.series[0].data = cpuHistory.value
          cpuChartOption.xAxis.data = timeHistory.value
        }
      } catch (error) {
        console.error('获取系统信息失败:', error)
        ElMessage.error('获取系统信息失败')
      }
    }

    // 获取系统日志
    const fetchSystemLogs = async () => {
      try {
        const response = await myAxios.get('/getLogs', {
          params: {
            lines: 200 // 默认获取200行日志
          }
        })
        console.log(response.data)
        if (response.data.code === 200) {
          // 处理返回的对象格式数据
          if (typeof response.data.data === 'object') {
            logs.value = Object.values(response.data.data)
          } else {
            logs.value = []
          }
          console.log(logs.value)
        }
      } catch (error) {
        console.error('获取系统日志失败:', error)
        ElMessage.error('获取系统日志失败')
      }
    }

    onMounted(() => {
      fetchSystemInfo()
      fetchSystemLogs()
      timer = setInterval(fetchSystemInfo, 5000)
    })

    onUnmounted(() => {
      if (timer) {
        clearInterval(timer)
      }
    })

    return {
      systemInfo,
      logs,
      cpuChartOption,
      formatLogEntry,
      getLogLevel
    }
  }
}
</script>

<style scoped>
.monitor {
  height: calc(100vh - 72px);
  width: 100%;
  background-color: #0f172a;
  color: #ffffff;
  padding: 20px;
  box-sizing: border-box;
}

.section {
  max-width: 960px;
  margin: 0 auto 20px;
  padding: 20px;
  background: #1e293b;
  border-radius: 8px;
  box-sizing: border-box;
}

.section-title {
  color: #3b82f6;
  font-size: 20px;
  margin-bottom: 20px;
  font-weight: 600;
}

.system-overview {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 20px;
  width: 100%;
}

.info-table {
  background: #0f172a;
  padding: 15px;
  border-radius: 8px;
  width: 100%;
}

.info-table table {
  width: 100%;
}

.info-table td {
  padding: 12px 8px;
  border-bottom: 1px solid #334155;
  word-wrap: break-word;
  word-break: break-all;
}

.info-table tr:last-child td {
  border-bottom: none;
}

.info-table td:first-child {
  color: #3b82f6;
  font-weight: 500;
}

.chart-container {
  background: #0f172a;
  padding: 20px;
  border-radius: 8px;
  width: 93.5%;
}

.chart-container h3 {
  color: #3b82f6;
  margin-bottom: 15px;
  font-size: 16px;
}

.cpu-chart {
  height: 300px;
  width: 100%;
}

.log-container {
  background: #0f172a;
  padding: 15px;
  border-radius: 8px;
  height: 400px;
  overflow-y: auto;
  font-family: Consolas, Monaco, 'Courier New', monospace;
  width: 96.7%;
}

.log-entry {
  padding: 8px 12px;
  font-size: 13px;
  line-height: 1.5;
  word-wrap: break-word;
  word-break: break-all;
  border-bottom: 1px solid #1e293b;
}

.log-entry:last-child {
  border-bottom: none;
}

.log-entry:hover {
  background: #1e293b;
}

.no-logs {
  text-align: center;
  padding: 20px;
  color: #64748b;
}

/* 日志级别样式 */
.log-debug {
  color: #94a3b8;
}

.log-info {
  color: #60a5fa;
}

.log-warning {
  color: #fbbf24;
}

.log-error {
  color: #ef4444;
}

/* echarts相关样式 */
:deep(.echarts-container) {
  width: 100% !important;
  height: 100% !important;
}

:deep(.echarts) {
  width: 100% !important;
  height: 100% !important;
}

/* 表格相关样式 */
:deep(.el-table) {
  background-color: transparent;
  color: #ffffff;
}

:deep(.el-table th.el-table__cell) {
  background-color: #1e293b;
  color: #ffffff;
}

:deep(.el-table tr) {
  background-color: transparent;
}

:deep(.el-table td.el-table__cell) {
  border-bottom: 1px solid #334155;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
}

::-webkit-scrollbar-track {
  background: #0f172a;
}

::-webkit-scrollbar-thumb {
  background: #334155;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #475569;
}
</style>